<template>
  <div class="data-table-container">
    <div class="data-table-card">
      <!-- 表格头部 -->
      <div class="data-table-header">
        <div class="data-table-title">
          <h3>
            <i class="pi pi-table"></i>
            数据列表
          </h3>
          <span class="data-count">共 {{ pagination.total }} 条数据</span>
        </div>
        <div class="data-table-actions">
          <Button 
            v-if="showRefresh"
            icon="pi pi-refresh" 
            label="刷新" 
            severity="secondary"
            size="small"
            @click="handleRefresh"
            :loading="loading"
          />
          <Button 
            v-if="showExport"
            icon="pi pi-download" 
            label="导出" 
            severity="secondary"
            size="small"
            @click="handleExport"
          />
          <Button 
            v-if="showAdd"
            icon="pi pi-plus" 
            label="新增" 
            severity="primary"
            size="small"
            @click="handleAdd"
          />
        </div>
      </div>
      
      <!-- 表格内容 -->
      <div class="data-table-content">
        <DataTable
          :value="data"
          :loading="loading"
          :paginator="false"
          :rows="pagination.pageSize"
          :totalRecords="pagination.total"
          :sortField="sortField"
          :sortOrder="sortOrder"
          :selectionMode="selectionMode"
          :selection="selection"
          @selection-change="handleSelectionChange"
          @row-select="handleRowSelect"
          @row-unselect="handleRowUnselect"
          @sort="handleSort"
          :class="tableClass"
          :stripedRows="stripedRows"
          :showGridlines="showGridlines"
          :responsiveLayout="responsiveLayout"
        >
          <!-- 选择列 -->
          <Column 
            v-if="selectionMode !== 'none'"
            selectionMode="multiple" 
            headerStyle="width: 3rem"
          />
          
          <!-- 序号列 -->
          <Column 
            v-if="showIndex"
            header="序号" 
            headerStyle="width: 4rem; text-align: center"
            bodyStyle="text-align: center"
          >
            <template #body="slotProps">
              {{ (pagination.currentPage - 1) * pagination.pageSize + slotProps.index + 1 }}
            </template>
          </Column>
          
          <!-- 数据列 -->
          <Column
            v-for="column in columns"
            :key="column.prop"
            :field="column.prop"
            :header="column.label"
            :sortable="column.sortable"
            :headerStyle="column.headerStyle"
            :bodyStyle="column.bodyStyle"
            :style="column.style"
            :class="column.class"
          >
            <template #body="slotProps">
              <div v-if="column.slot" class="column-slot">
                <slot 
                  :name="column.slot" 
                  :row="slotProps.data" 
                  :index="slotProps.index"
                  :column="column"
                />
              </div>
              <div v-else-if="column.formatter" class="column-formatted">
                {{ column.formatter(slotProps.data[column.prop], slotProps.data, slotProps.index) }}
              </div>
              <div v-else-if="column.type === 'tag'" class="column-tag">
                <Tag 
                  :value="slotProps.data[column.prop]"
                  :severity="getTagSeverity(slotProps.data[column.prop], column)"
                  :class="column.tagClass"
                />
              </div>
              <div v-else-if="column.type === 'badge'" class="column-badge">
                <Badge 
                  :value="slotProps.data[column.prop]"
                  :severity="getBadgeSeverity(slotProps.data[column.prop], column)"
                  :class="column.badgeClass"
                />
              </div>
              <div v-else-if="column.type === 'link'" class="column-link">
                <a 
                  :href="getLinkHref(slotProps.data, column)"
                  :target="column.target || '_self'"
                  :class="column.linkClass"
                  @click="handleLinkClick(slotProps.data, column, $event)"
                >
                  {{ slotProps.data[column.prop] }}
                </a>
              </div>
              <div v-else-if="column.type === 'image'" class="column-image">
                <img 
                  :src="slotProps.data[column.prop]"
                  :alt="column.alt || slotProps.data[column.prop]"
                  :class="column.imageClass"
                  :style="column.imageStyle"
                  @error="handleImageError"
                />
              </div>
              <div v-else class="column-text">
                {{ slotProps.data[column.prop] }}
              </div>
            </template>
          </Column>
          
          <!-- 操作列 -->
          <Column 
            v-if="showActions && actions.length > 0"
            header="操作" 
            headerStyle="width: 8rem; text-align: center"
            bodyStyle="text-align: center"
            :frozen="actionsFrozen"
            alignFrozen="right"
          >
            <template #body="slotProps">
              <div class="action-buttons">
                <Button
                  v-for="action in actions"
                  :key="action.key"
                  :icon="action.icon"
                  :label="action.label"
                  :severity="action.severity || 'secondary'"
                  :size="action.size || 'small'"
                  :disabled="action.disabled && action.disabled(slotProps.data, slotProps.index)"
                  :loading="action.loading && action.loading(slotProps.data, slotProps.index)"
                  :class="action.class"
                  @click="handleAction(action, slotProps.data, slotProps.index)"
                />
              </div>
            </template>
          </Column>
        </DataTable>
      </div>
      
      <!-- 分页器 -->
      <div v-if="showPagination" class="data-table-pagination">
        <Paginator
          :rows="pagination.pageSize"
          :totalRecords="pagination.total"
          :first="(pagination.currentPage - 1) * pagination.pageSize"
          :rowsPerPageOptions="rowsPerPageOptions"
          @page="handlePageChange"
          :template="paginationTemplate"
          :class="paginationClass"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Button from 'primevue/button'
import Tag from 'primevue/tag'
import Badge from 'primevue/badge'
import Paginator from 'primevue/paginator'

export interface TableColumn {
  prop: string
  label: string
  sortable?: boolean
  type?: 'text' | 'tag' | 'badge' | 'link' | 'image'
  slot?: string
  formatter?: (value: any, row: any, index: number) => string
  headerStyle?: string
  bodyStyle?: string
  style?: string
  class?: string
  // 标签相关
  tagClass?: string
  tagSeverity?: (value: any) => string
  // 徽章相关
  badgeClass?: string
  badgeSeverity?: (value: any) => string
  // 链接相关
  target?: string
  linkClass?: string
  href?: (row: any) => string
  // 图片相关
  alt?: string
  imageClass?: string
  imageStyle?: string
}

export interface TableAction {
  key: string
  label: string
  icon?: string
  severity?: 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'danger'
  size?: 'small' | 'large'
  class?: string
  disabled?: (row: any, index: number) => boolean
  loading?: (row: any, index: number) => boolean
  handler: (row: any, index: number) => void
}

export interface Pagination {
  currentPage: number
  pageSize: number
  total: number
}

interface Props {
  data: any[]
  columns: TableColumn[]
  pagination: Pagination
  loading?: boolean
  selectionMode?: 'single' | 'multiple' | 'none'
  selection?: any[]
  showIndex?: boolean
  showActions?: boolean
  showPagination?: boolean
  showRefresh?: boolean
  showExport?: boolean
  showAdd?: boolean
  actions?: TableAction[]
  actionsFrozen?: boolean
  stripedRows?: boolean
  showGridlines?: boolean
  responsiveLayout?: 'scroll' | 'stack'
  tableClass?: string
  paginationClass?: string
  rowsPerPageOptions?: number[]
  paginationTemplate?: string
}

interface Emits {
  (e: 'update:selection', selection: any[]): void
  (e: 'page-change', page: number, pageSize: number): void
  (e: 'sort', sortField: string, sortOrder: number): void
  (e: 'refresh'): void
  (e: 'export'): void
  (e: 'add'): void
  (e: 'action', action: TableAction, row: any, index: number): void
  (e: 'link-click', row: any, column: TableColumn, event: Event): void
}

const props = withDefaults(defineProps<Props>(), {
  data: () => [],
  columns: () => [],
  pagination: () => ({ currentPage: 1, pageSize: 10, total: 0 }),
  loading: false,
  selectionMode: 'none',
  selection: () => [],
  showIndex: true,
  showActions: true,
  showPagination: true,
  showRefresh: true,
  showExport: false,
  showAdd: false,
  actions: () => [],
  actionsFrozen: true,
  stripedRows: true,
  showGridlines: false,
  responsiveLayout: 'scroll',
  tableClass: '',
  paginationClass: '',
  rowsPerPageOptions: () => [10, 20, 50, 100],
  paginationTemplate: 'FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink RowsPerPageDropdown'
})

const emit = defineEmits<Emits>()

const sortField = ref('')
const sortOrder = ref(1)

// 处理选择变化
const handleSelectionChange = (event: any) => {
  emit('update:selection', event.value)
}

// 处理行选择
const handleRowSelect = (event: any) => {
  // 可以在这里添加行选择的逻辑
}

// 处理行取消选择
const handleRowUnselect = (event: any) => {
  // 可以在这里添加行取消选择的逻辑
}

// 处理排序
const handleSort = (event: any) => {
  sortField.value = event.sortField
  sortOrder.value = event.sortOrder
  emit('sort', event.sortField, event.sortOrder)
}

// 处理分页变化
const handlePageChange = (event: any) => {
  const page = Math.floor(event.first / event.rows) + 1
  emit('page-change', page, event.rows)
}

// 处理刷新
const handleRefresh = () => {
  emit('refresh')
}

// 处理导出
const handleExport = () => {
  emit('export')
}

// 处理新增
const handleAdd = () => {
  emit('add')
}

// 处理操作
const handleAction = (action: TableAction, row: any, index: number) => {
  // 只通过emit触发，避免双重调用
  emit('action', action, row, index)
}

// 处理链接点击
const handleLinkClick = (row: any, column: TableColumn, event: Event) => {
  emit('link-click', row, column, event)
}

// 处理图片错误
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
}

// 获取标签严重程度
const getTagSeverity = (value: any, column: TableColumn) => {
  if (column.tagSeverity) {
    return column.tagSeverity(value)
  }
  return 'secondary'
}

// 获取徽章严重程度
const getBadgeSeverity = (value: any, column: TableColumn) => {
  if (column.badgeSeverity) {
    return column.badgeSeverity(value)
  }
  return 'info'
}

// 获取链接地址
const getLinkHref = (row: any, column: TableColumn) => {
  if (column.href) {
    return column.href(row)
  }
  return '#'
}
</script>

<style scoped>
.data-table-container {
  margin-bottom: 16px;
}

.data-table-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  overflow: hidden;
}

.data-table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.data-table-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.data-table-title h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.data-table-title h3 i {
  color: #1890ff;
}

.data-count {
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  padding: 4px 8px;
  border-radius: 4px;
}

.data-table-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 按钮样式覆盖 */
.data-table-actions :deep(.p-button) {
  height: 32px;
  padding: 6px 12px;
  font-size: 12px;
}

.data-table-content {
  padding: 0;
}

.column-slot,
.column-formatted,
.column-tag,
.column-badge,
.column-link,
.column-image,
.column-text {
  display: flex;
  align-items: center;
  min-height: 32px;
}

.column-link a {
  color: #1890ff;
  text-decoration: none;
  transition: color 0.3s;
}

.column-link a:hover {
  color: #40a9ff;
}

.column-image img {
  max-width: 40px;
  max-height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 3px;
  flex-wrap: wrap;
}

/* 表格内操作按钮样式 */
.action-buttons :deep(.p-button) {
  height: 28px;
  padding: 4px 8px;
  font-size: 11px;
}

.data-table-pagination {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  justify-content: center;
}

/* 分页器按钮样式 */
.data-table-pagination :deep(.p-paginator) {
  font-size: 12px;
}

.data-table-pagination :deep(.p-paginator .p-paginator-page) {
  min-width: 28px;
  height: 28px;
  font-size: 12px;
}

.data-table-pagination :deep(.p-paginator .p-paginator-first),
.data-table-pagination :deep(.p-paginator .p-paginator-prev),
.data-table-pagination :deep(.p-paginator .p-paginator-next),
.data-table-pagination :deep(.p-paginator .p-paginator-last) {
  width: 28px;
  height: 28px;
  font-size: 12px;
}

.data-table-pagination :deep(.p-dropdown) {
  height: 28px;
  font-size: 12px;
}

.data-table-pagination :deep(.p-dropdown .p-dropdown-label) {
  padding: 4px 8px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .data-table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .data-table-actions {
    width: 100%;
    justify-content: flex-end;
    flex-wrap: wrap;
  }
  
  .data-table-pagination {
    padding: 10px 12px;
  }
  
  .action-buttons {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .data-table-header {
    padding: 12px 16px;
  }
  
  .data-table-pagination {
    padding: 6px 8px;
  }
  
  .data-table-actions {
    gap: 3px;
  }
  
  .action-buttons {
    gap: 2px;
  }
}

/* 表格样式覆盖 */
:deep(.p-datatable) {
  border: none;
}

:deep(.p-datatable .p-datatable-header) {
  background: transparent;
  border: none;
  padding: 0;
}

:deep(.p-datatable .p-datatable-thead > tr > th) {
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  color: #333;
  font-weight: 600;
  font-size: 12px;
}

:deep(.p-datatable .p-datatable-tbody > tr > td) {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 16px;
  font-size: 12px;
}

:deep(.p-datatable .p-datatable-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.p-datatable .p-datatable-tbody > tr.p-highlight > td) {
  background: #e6f7ff;
}

:deep(.p-paginator) {
  background: transparent;
  border: none;
  padding: 0;
}
</style>
